<template>
  <div>
    <el-card>
      <el-row type="flex">
        <el-col>
          <el-button size="small" type="primary" @click="isShowDialog = true">添加房产</el-button>
        </el-col>
        <el-col>
          <el-row type="flex">
            <el-select v-model="searchOption.category">
              <el-option
                :value="''"
                :label="'全部分类'"
              />
              <el-option
                v-for="category in categories"
                :key="category.id"
                :value="category.id"
                :label="category.title"
              />
            </el-select>
            <el-select v-model="searchOption.agent">
              <el-option
                :value="''"
                :label="'全部经纪'"
              />
              <el-option
                v-for="agent in agents"
                :key="agent.id"
                :value="agent.id"
                :label="agent.name"
              />
            </el-select>
            <el-input v-model="searchOption.title" placeholder="请输入关键字" />
            <el-button @click="search">
              筛选
            </el-button>
          </el-row>
        </el-col>
      </el-row>
      <el-divider />
      <el-table
        :data="properties"
        border
      >
        <el-table-column label="封面">
          <template #default="{row}">
            <img :src="row.image" alt="" style="width:200px;height:200px;object-fit:cover;">
          </template>
        </el-table-column>
        <el-table-column label="标题" prop="title" />
        <el-table-column label="标签" prop="tag">
          <template #default="{row}">
            <el-tag v-for="tag in row.tags" :key="tag" type="success">{{ tag }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="地址" prop="address" />
        <el-table-column label="分类" prop="category.title" />
        <el-table-column label="经纪" prop="agent.name" />
        <el-table-column label="价格" prop="price" />
        <el-table-column label="介绍" prop="desc" />
        <el-table-column label="图片">
          <template #default="{row}">
            <el-row type="flex">
              <el-row v-for="(src, index) in row.photos" :key="index" :span="8">
                <img :src="src" alt="" style="width:48px;height:48px;object-fit:cover;">
              </el-row>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{row}">
            <el-button size="mini" type="primary" @click="updateProperty(row.id)">编辑</el-button>
            <el-button size="mini" type="danger" @click="delProperty(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-divider />
      <el-row type="flex" justify="center">
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="pagination._limit"
          @current-change="currentChange"
        />
      </el-row>
    </el-card>
    <el-dialog :title="`${data.id?'编辑':'添加'}房产`" :visible="isShowDialog" destroy-on-close @close="btnClose">
      <el-form ref="form" :model="data" :rules="rules">
        <el-form-item label-width="68px" label="经纪">
          <el-select v-model="data.agent">
            <el-option
              v-for="agent in agents"
              :key="agent.id"
              :value="agent.id"
              :label="agent.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label-width="68px" label="分类">
          <el-select v-model="data.category">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :value="category.id"
              :label="category.title"
            />
          </el-select>
        </el-form-item>
        <el-form-item label-width="68px" label="标题" prop="title">
          <el-input v-model="data.title" />
        </el-form-item>
        <el-form-item label-width="68px" label="标签" prop="tag">
          <el-tag
            v-for="tag in dynamicTags"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
        </el-form-item>
        <el-form-item label-width="68px" label="地址" prop="address">
          <el-row type="flex">
            <el-cascader
              v-model="value"
              style="width: 140px"
              placeholder="选择区域"
              :options="areas"
              @change="(res)=>{
                data.address = res.join(',')
                value = []
                $refs.areaInput.focus()
              }"
            />
            <el-input ref="areaInput" v-model="data.address" />
          </el-row>
        </el-form-item>
        <el-form-item label-width="68px" label="价格" prop="price">
          <el-input v-model="data.price" />
        </el-form-item>
        <el-form-item label-width="68px" label="描述" prop="desc">
          <el-input v-model="data.desc" :autosize="{ minRows: 4, maxRows: 8}" resize="none" type="textarea" />
        </el-form-item>
        <el-form-item label-width="68px" label="内容" prop="content">
          <vue-editor v-model="data.content" />
        </el-form-item>
        <el-form-item label-width="68px" label="介绍图片">
          <div style="padding-left:40px">
            <ImageUpload ref="photos" :single="false" />
          </div>
        </el-form-item>
        <el-form-item label-width="68px" label="封面">
          <div style="padding-left:40px">
            <ImageUpload ref="upload" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" type="primary" @click="btnOK">确定</el-button>
        <el-button size="small" @click="btnClose">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { addProperty, delProperty, getProperties, getPropertiesCount, getPropertyDetail, updateProperty } from '@/api/property'
import { getAgents } from '@/api/agent'
import Axios from 'axios'
import { getCategories } from '@/api/category'
export default {
  data() {
    return {
      categories: [],
      value: '',
      areas: [],
      searchOption: {
        title: '',
        agent: '',
        category: ''
      },
      searchOptionConfirmed: {
        title: '',
        agent: '',
        category: ''
      },
      properties: [],
      pagination: {
        _limit: 2,
        _start: 0
      },
      agents: [],
      total: 0,
      isShowDialog: false,
      dynamicTags: [],
      data: {
        title: '',
        desc: '',
        tag: '',
        address: '',
        price: '',
        content: '',
        agent: '',
        image: '',
        category: ''
      },
      inputVisible: true,
      inputValue: '',
      rules: {
        title: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    searchOption: {
      deep: true,
      immediate: true,
      handler() {
        this.searchOptionConfirmed = {}
        for (const key in this.searchOption) {
          if (this.searchOption[key]) {
            this.searchOptionConfirmed[`${key}_contains`] = this.searchOption[key]
          }
        }
      }
    }
  },
  async created() {
    this.getProperties()
    this.getAgents()
    this.getCategories()
    const res = await Axios.get('https://restapi.amap.com/v3/config/district?key=60e00996dec1e73abda4333570328ef8&subdistrict=3')
    this.areas = res.data.districts[0].districts.map(area => {
      return {
        value: area.name,
        label: area.name,
        children: area.districts.map(area => {
          return {
            value: area.name,
            label: area.name,
            children: area.districts.map(area => {
              return {
                value: area.name,
                label: area.name
              }
            })
          }
        })
      }
    })
  },
  methods: {
    async getCategories() {
      this.categories = await getCategories({
        _limit: -1
      })
    },
    async getAgents() {
      this.agents = await getAgents({
        _limit: -1
      })
    },
    async getProperties() {
      this.properties = await getProperties({
        ...this.pagination,
        ...this.searchOptionConfirmed
      })
      this.total = await getPropertiesCount({
        ...this.pagination,
        ...this.searchOptionConfirmed
      })
    },
    currentChange(newPage) {
      this.pagination._start = (newPage - 1) * this.pagination._limit
      this.getProperties()
    },
    async delProperty(id) {

      await delProperty(id)
      this.$message.success('删除成功')
      this.getProperties()
    },
    async updateProperty(id) {
      const res = await getPropertyDetail(id)
      this.data = {
        ...res,
        agent: res.agent?.id,
        category: res.category?.id
      }
      this.dynamicTags = this.data.tags ? [...this.data.tags] : []
      this.isShowDialog = true
      this.$nextTick(() => {
        if (this.data.image) {
          this.$refs.upload.fileList = [
            { url: this.data.image }
          ]
        }
        if (this.data.photos?.length > 0) {
          this.$refs.photos.fileList = this.data.photos.map(url => ({ url }))
        }
      })
    },
    async btnOK() {
      await this.$refs.form.validate()
      this.data.image = this.$refs.upload.fileList[0]?.url
      this.data.photos = this.$refs.photos.fileList?.map(img => img.url)
      this.data.tags = [...this.dynamicTags]
      if (this.data.id) {
        await updateProperty(this.data)
      } else {
        await addProperty(this.data)
      }
      this.$message.success('操作成功')
      this.isShowDialog = false
      this.getProperties()
    },
    btnClose() {
      this.data = {}
      this.dynamicTags = []
      this.isShowDialog = false
    },
    search() {
      this.getProperties()
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style lang="scss">
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
